
// 后台访问API
const express = require('express')
const router = express.Router()
const Cookies = require('cookies')
const User = require('../models/User')
const Article = require('../models/Article')
const Category = require('../models/Category')
const moment = require('moment')

const JwtUtil = require('../utils/token.js')

// 统一返回格式
let responseData
// 后台登录拦截器
router.use(function(req, res, next) {
	// 初始化响应数据
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	console.log(req.path)
	// 进行路由判断，如果是登录页，则不进行拦截，如果不是登录页，判断token.验证用户是否已经登录
	if(req.path !== '/login') {
 		let token = req.headers.token;
    let jwt = new JwtUtil(token);
    let result = jwt.verifyToken();
    // 如果考验通过就next，否则就返回登陆信息不正确
    if (result == 'err') {
        console.log(result);
        responseData.resultCode = 1
				responseData.resultMsg = '登录已过期，请重新登录'
				res.json(responseData)
				return
    }
	}
	next()
})

/** 
 * 后台登录接口 /admin/login
 * 
 */
router.post('/login', function(req, res, next) {
	console.log(req.param('username'))
	console.log(req.body)
	const { username, password } = req.body
	console.log(username, password)
	if(!username || !password) {
		responseData.resultCode = 1
		responseData.resultMsg = '用户名或者密码不能为空'
		res.json(responseData)
		return
	}
	User.find().then((res) => {console.log(res)})
	User.findOne({
		username: username,
		password: password,
		isAdmin: true
	}).then(function(userInfo) {
		console.log('---', userInfo)
		if(!userInfo) {
			responseData.resultCode = 1
			responseData.resultMsg = '用户名或者密码错误'
			res.json(responseData)
			return
		}
		responseData.resultMsg = '登录成功'
		// 这里登录成功之后应该生成一个token值给用户
		// 将用户id传入并生成token
    let jwt = new JwtUtil(userInfo._id);
    let token = jwt.generateToken();
    // 将 token 返回给客户端
    responseData.data['token'] = token
    responseData.data['username'] = userInfo.username
		res.json(responseData)
	})
})

// 数据分析
router.get('/dataAnalysis', function(req, res, next) {
	responseData = {
		resultCode: 0,
		resultMsg: 'success',
		data: {}
	}
	let result = []
	let promises = []
	let seven = {
		0: 0,
		1: 0,
		2: 0,
		3: 0,
		4: 0,
		5: 0,
		6: 0
	}
	Category.find().then(function(CategoryList) {
		CategoryList.forEach(function(item, index) {
			promises.push(new Promise(function(resolve, reject) {
				Article.count({
					articleTag: item.categoryName
				}).then(function(totalNum) {
					result.push({name: item.categoryName, value: totalNum})
					resolve()
				})
			}))
		})
		Promise.all(promises).then(function() {
			responseData.data.list = result
			Article.find().then(function(ArticleList) {
				ArticleList.forEach((item, index) => {
					var diff = moment(moment() - moment(item.articleTime)).format('DD') - 1
					console.log(diff, item.articleTime)
					if(diff < 7) {
						seven[diff]++
					}
				})
				responseData.data.seven = seven
				res.send(responseData)
			})
		
		})
	})

})




router.use('/article', require('./article/index.js'))
router.use('/category', require('./category/index.js'))
router.use('/users', require('./user/index.js'))
router.use('/comment', require('./comment/index.js'))






module.exports = router